package com.note.backend.service.impl.file;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.note.backend.mapper.RepositoryMapper;
import com.note.backend.pojo.Repository;
import com.note.backend.service.file.RepositoryService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@RequiredArgsConstructor
@Service
public class RepositoryServiceImpl implements RepositoryService {

    private final RepositoryMapper repositoryMapper;

    @Override
    public Repository createRepository(String name, String description, Integer userId) {
        Repository repository = new Repository();
        repository.setName(name);
        repository.setDescription(description);
        repository.setUserId(userId);
        repository.setCreateTime(LocalDateTime.now());
        repository.setUpdateTime(LocalDateTime.now());

        int result = repositoryMapper.insert(repository);
        if (result <= 0) {
            throw new RuntimeException("创建知识库失败");
        }
        return repository;
    }

    @Override
    public List<Repository> getRepositoriesByUserId(Integer userId) {
        QueryWrapper<Repository> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.orderByDesc("update_time");
        return repositoryMapper.selectList(queryWrapper);
    }

    @Override
    public Repository getRepositoryById(Integer id) {
        Repository repository = repositoryMapper.selectById(id);
        if (repository == null) {
            throw new RuntimeException("知识库不存在");
        }
        return repository;
    }

    @Override
    public void deleteRepository(Integer id, Integer userId) {
        QueryWrapper<Repository> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id).eq("user_id", userId);

        int result = repositoryMapper.delete(queryWrapper);
        if (result <= 0) {
            throw new RuntimeException("删除知识库失败");
        }
    }
}